package cn.siriusbot.siriuspro.web.websocket;

import cn.siriusbot.siriuspro.bot.plugin.ExpandClient;
import cn.siriusbot.siriuspro.bot.plugin.PlugInClient;
import cn.siriusbot.siriuspro.bot.plugin.PlugInFactory;
import cn.siriusbot.siriuspro.uitls.AppContextUtil;
import cn.siriusbot.siriuspro.web.websocket.surface.WebsocketSession;
import cn.siriusbot.siriuspro.web.websocket.surface.WebsocketSessionImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * 拓展WebSocket
 */
@Component
@ServerEndpoint(value = "/expand-websocket/{packageName}")
@Log4j2
public class OneExpandWebSocketServer {

    PlugInFactory factory;

    private ExpandClient expandClient;

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    private WebsocketSession websocketSession;

    @OnOpen
    public void onOpen(@PathParam("packageName") String packageName, Session session) {
        this.session = session;
        this.websocketSession = new WebsocketSessionImpl(session);
        this.factory = AppContextUtil.getBean(PlugInFactory.class);
        final PlugInClient client = this.factory.getPlugInClientByPackageName(packageName);
        if (client == null) {
            log.warn(String.format("连接ws时错误，找不到包名为[%s]的应用", packageName));
            try {
                session.close();
            } catch (IOException e) {
                log.error("关闭ws连接时发生错误", e);
            }
            return;
        }
        if (!(client instanceof ExpandClient expandClient)) {
            log.warn(String.format("连接ws时错误，应用[%s]的未实现ExpandClient接口，无法接入ws", packageName));
            try {
                session.close();
            } catch (IOException e) {
                log.error("关闭ws连接时发生错误", e);
            }
            return;
        }
        this.expandClient = expandClient;
        this.expandClient.putWebSocketOpen(this.websocketSession);
    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("ws-message -> " + message);
        if (this.expandClient != null) this.expandClient.putWebSocketMessage(websocketSession, message);
    }

    @OnClose
    public void onClose() {
        if (this.expandClient != null) this.expandClient.putWebSocketClose(this.websocketSession);
    }
}
